package com.vidmt.api.modules.sys.auth.pwdstrategy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vidmt.api.common.utils.HashUtils;
import com.vidmt.api.modules.sys.auth.DefaultPwdStrategy;

public class HashStrategy extends DefaultPwdStrategy {
	private static Logger log = LoggerFactory.getLogger(HashStrategy.class);

	private PasswordType pwdType;

	public HashStrategy(PasswordType pwdType) {
		this.pwdType = pwdType;
	}

	public enum PasswordType {
		/**
		 * The password is stored as a hex-encoded MD5 hash.
		 */
		md5,

		/**
		 * The password is stored as a hex-encoded SHA-1 hash.
		 */
		sha1,

		/**
		 * The password is stored as a hex-encoded SHA-256 hash.
		 */
		sha256,

		/**
		 * The password is stored as a hex-encoded SHA-512 hash.
		 */
		sha512;
	}

	public static String hashPwd(String pwd, String salt, PasswordType hashType) {
		if (hashType == PasswordType.md5) {
			return HashUtils.hash(pwd, salt, "MD5");
		} else if (hashType == PasswordType.sha1) {
			return HashUtils.hash(pwd, salt, "SHA-1");
		} else if (hashType == PasswordType.sha256) {
			return HashUtils.hash(pwd, salt, "SHA-256");
		} else if (hashType == PasswordType.sha512) {
			return HashUtils.hash(pwd, salt, "SHA-512");
		}
		throw new IllegalArgumentException("invalid hashtype:" + hashType);
	}

	@Override
	public String getAlg() {
		return pwdType.name();
	}

	@Override
	public String getCyphered(String rawkey, String plainpwd) {
		return hashPwd(plainpwd, rawkey, pwdType);
	}
}
